<template>
	<uv-popup ref="popup" mode="center" bg-color="#fff" closeable z-index="999">
		<view class="content">
			<uv-checkbox-group v-model="checkboxValue">
				<uv-checkbox :customStyle="{marginBottom: '8px'}" v-for="(item, index) in chapterList" :key="index" :label="item.name" :name="item.chapter"></uv-checkbox>
			</uv-checkbox-group>
			<uv-button text="取消" @click="close"></uv-button>
			<uv-button text="保存" :loading="btnLoading" loading-text="保存中..." type="primary" @click="save"></uv-button>
		</view>
	</uv-popup>
</template>
<script setup>
	import { ref, watch } from 'vue';
	import { changeChapter } from '/common/api/user.js';
	const emits = defineEmits(['reloadData']);
	const popup = ref(null);
	const checkboxValue = ref([]);
	const btnLoading = ref(false);
	const props = defineProps({
		chapterList: {
			type: Array,
			defaul() {
				return []
			}
		},
		selectChapterList: {
			type: Array,
			defaul() {
				return []
			}
		}
	})
	watch(() => props.selectChapterList, (newVal) => {
		if (newVal && newVal.length) {
			newVal.forEach(item => {
				checkboxValue.value.push(item.chapter)
			})
		}
	}, { immediate: true })
	async function save() {
		btnLoading.value = true;
		let nots = props.chapterList.filter(item => !checkboxValue.value.find(item2 => item2 === item.chapter));
		const chapters_nots = nots.filter(item => item.type != 'CUSTOM' && !checkboxValue.value.find(item2 => item2 === item.chapter)).map(item => item.chapter);
		const chapters_custom_nots = nots.filter(item => item.type == 'CUSTOM' && !checkboxValue.value.find(item2 => item2 === item.chapter)).map(item => item.chapter);
		const res = await changeChapter({
			chapters: checkboxValue.value,
			chapters_nots,
			chapters_custom_nots,
			uid: uniCloud.getCurrentUserInfo().uid
		})
		btnLoading.value = false;
		uni.$emit('initData');
		emits('reloadData');
		close();
	}

	function open() {
		popup.value.open();
	}

	function close() {
		popup.value.close();
	}
	defineExpose({ open })
</script>
<style scoped lang="scss">
	.content {
		width: 1000px;
		height: 600px;
	}
</style>